#pragma once
#include "uart/ProtocolSender.h"
#include "storage/StoragePreferences.h"
#include "net/NetManager.h"
#include "logic_utility.hpp"
#include "misc/image_cache.h"
#include "os/SystemProperties.h"
#include <base/time.hpp>
#include "ctime"
#include <time.h>
#include "water/self_mode.h"
#include "manager/hardware.h"
#include "manager/ConfigManager.h"
#include "uart/ProtocolData.h"
#include "water/timer_event.h"
#include <base/files.hpp>



static SWaterOption _s_cur_opt;
static SWaterParam _s_cur_param = {E_WATER_MODE_COMMON_WATER, 150, 25};


//蜂鸣器叫喊
class BeepThread: public Thread {
private:
	int _beefCount = 0;

	int _sleep_time = 500;

public:
	virtual bool readyToRun() {
		 return true;
	}

	void setBeepCount(int count){
		_beefCount = count;
	}
	void setSleepTime(int sleep_time){
		_sleep_time = sleep_time;
	}

	virtual bool threadLoop() {
		//检查是否有退出线程的请求，如果有，则返回false，立即退出线程
		if (exitPending()) {
			return false;
		}
		if(_beefCount > 0){
			--_beefCount;
			hw::beep();
			if(_beefCount > 0){	//最后一声就不延时了
				sleep(_sleep_time);
			}
			return true;
		}
		return false;
	}
};

static BeepThread beep_thread;

void set_beep_count(int count, int sleep_time_ms) //count 响应次数 sleep_time_ms 每次sleep_time_ms后响应（ms）
{
	beep_thread.setSleepTime(sleep_time_ms);
	beep_thread.setBeepCount(count);
	beep_thread.run("beep");
}

void hideWaterWnd(){
	mWaterWndPtr->hideWnd();
}

//首次上电冲洗
static void PowerFirstWash(){
	int firstup = 0;
	SystemProperties::getInt("sys.zkapp.firstup", &firstup, 0);
	if(firstup == 0){
//		LOGD("--------------------进冲洗------------------------");
		if(is_can_start_auto_timer(E_TIMER_EVENT_ID_FILTER_BRASH)){
			//上电首次冲洗
			SystemProperties::setInt("sys.zkapp.firstup", 1);
			water::start_timer_event(E_TIMER_EVENT_FILTER_BRASH);
		}
	}
}

class PowerOnThread: public Thread {
 public:

   virtual bool readyToRun() {
     LOGD("准备冲洗Thread 已经创建完成");
     return true;
   }

   virtual bool threadLoop() {
//     LOGD("线程循环函数");

     //检查是否有退出线程的请求，如果有，则返回false，立即退出线程
     if (exitPending()) {
       return false;
     }

     if(Global::Flags::Serial_flag) {
    	 PowerFirstWash();
    	 return false;
     }

     sleep(100);

     return true;
   }
};
static PowerOnThread brash_thread;


void ui_water_output(bool _switch){
	if(_switch){
		mTextWaterPtr->setText("出水中");
		moutWaterPtr->setSelected(true);
	}else{
		mTextWaterPtr->setText("出水");
		moutWaterPtr->setSelected(false);
	}
}

void ui_iceing_output(bool _switch){
	if(_switch){
		mTextWaterPtr->setText("出冰中");
		moutIcePtr->setSelected(true);
	}else{
		mTextWaterPtr->setText("出冰");
		moutIcePtr->setSelected(false);
	}
}


//停水操作
bool stop_water_output(int water_num, bool is_auto_stop = false) {
    // 如果防干烧定时器事件正在运行，则停止该事件
    if (water::is_timer_event_running(E_TIMER_EVENT_WATER_PREVENT_DRY_BURNING)) {
        water::stop_timer_event(E_TIMER_EVENT_WATER_PREVENT_DRY_BURNING);
        // 以下代码被注释掉，可能是为了防止递归调用或特殊处理
        // stop_water_output(Global::Water::water_value < _s_cur_param.water_output ?
        //                  Global::Water::water_value : _s_cur_param.water_output, true);
        // return false;
    }

    // 如果不是自动停水（手动停水）
    if (!is_auto_stop) {
        // 如果当前设备处于热水状态
        if (water::get_water_state() == E_WATER_STATE_HOT_WATER) {
            // 如果当前水温为60℃、65℃、70℃、75℃、80℃或85℃
            if (_s_cur_param.water_temp == 60 || _s_cur_param.water_temp == 65 ||
                _s_cur_param.water_temp == 70 || _s_cur_param.water_temp == 75 ||
                _s_cur_param.water_temp == 80 || _s_cur_param.water_temp == 85) {

                // 出两秒95℃的水（可能是为了清理管道或满足特定需求）
                protocol::startOutputWater(95, _s_cur_param.water_output, true, false);

                // 启动热水延时定时器事件
                water::start_timer_event(E_TIMER_EVENT_WATER_HOT_WATER_DELAY);

                return false;  // 返回失败，表示需要等待热水延时完成
            }
        }
    }

    // 停止LED灯自动关闭的定时器事件，并重新启动它
    water::stop_timer_event(E_TIMER_EVENT_WATER_LED_OFF);
    if(Global::Water::ledType){
    	water::start_timer_event(E_TIMER_EVENT_WATER_LED_OFF, Global::Water::ledTime);
    	// LED照明灯在出水结束后若1分钟内无任何操作时自动关闭
    }


    // 停止零陈水A的定时器事件，并重新启动它
    water::stop_timer_event(E_TIMER_EVENT_ZERO_STATE_WATER_A);
    water::start_timer_event(E_TIMER_EVENT_ZERO_STATE_WATER_A);

    // 关闭TDS传感器
    protocol::setTds(false, false);

    // 根据当前设备的工作状态，执行不同的停水逻辑
    if (water::get_water_state() == E_WATER_STATE_ICE_WATER) {
        // 如果当前是冰水状态
        // 记录出水量
        water::add_flowmeter_data(water_num);

        // 关闭冰水相关的设备负载
        water::set_task_load(E_TASK_ID_WATER_OPERATE, false, {E_DEV_LOAD_TYPE_DIAPHRAGM_PUMP, E_DEV_LOAD_TYPE_CLEANTANK2});

    } else if (water::get_water_state() == E_WATER_STATE_COMMON_WATER) {
        // 如果当前是常温水状态
        // 记录出水量
        water::add_flowmeter_data(water_num);

        // 关闭常温水相关的设备负载
        water::set_task_load(E_TASK_ID_WATER_OPERATE, false,
                             {E_DEV_LOAD_TYPE_COMMON_TEMP, E_DEV_LOAD_TYPE_WATER_IN, E_DEV_LOAD_TYPE_AIR_PUMP});

    } else if (water::get_water_state() == E_WATER_STATE_HOT_WATER) {
        // 如果当前是热水状态
        // 记录热水出水量
        water::add_hot_water_data(water_num);

        // 关闭热水相关的设备负载
        water::set_task_load(E_TASK_ID_WATER_OPERATE, false,
                             {E_DEV_LOAD_TYPE_UV_LIGHT, E_DEV_LOAD_TYPE_WATER_IN, E_DEV_LOAD_TYPE_AIR_PUMP});
    }

    // 停止出水
    protocol::stopOutputWater();

    // 设置设备状态为空闲（待机）
    water::set_water_state(E_WATER_STATE_IDLE);

    // 保存滤芯数据
    water::cartridge_data_save();

    // 开启屏幕自动计数功能
    LOCK_SCREEN->set_auto_count(true);

    // 更新UI，隐藏出水状态
    ui_water_output(false);

    return true;  // 返回成功
}


//出水操作
bool start_water_output() {
		// 清除滤芯寿命警告标志
	    Global::Flags::is_warn_cartridge_dying = false;

	    // 如果滤芯过期警告已打开，则清除该警告
	    if (Global::Flags::is_open_warn_cartridge_over)
	        Global::Flags::is_warn_cartridge_over = false;

	    // 判断当前模式和水温，执行不同的出水逻辑
	    if (_s_cur_param.mode == E_WATER_MODE_COMMON_WATER || _s_cur_param.water_temp == 25) {
	        // 常温水模式 或 水温为 25℃
	        // 检查是否可以启动定时器事件 "出水流量计1"
	        if (!is_can_start_auto_timer(E_TIMER_EVENT_ID_WATER_OPERATE_OTHER)) {
	        	LOGW_TRACE("出水常温水操作失败");
	            return false;  // 如果无法启动，则直接返回失败
	        }

	        // 停止零陈水A和LED灯自动关闭的定时器事件
	        water::stop_timer_event(E_TIMER_EVENT_ZERO_STATE_WATER_A);
	        water::stop_timer_event(E_TIMER_EVENT_WATER_LED_OFF);

	        // 设置任务负载，开启常温水相关的设备负载
	        water::set_task_load(E_TASK_ID_WATER_OPERATE, true,
	                             {E_DEV_LOAD_TYPE_COMMON_TEMP, E_DEV_LOAD_TYPE_WATER_IN,
	                              E_DEV_LOAD_TYPE_AIR_PUMP, E_DEV_LOAD_TYPE_LED_LIGHT});

	        // 设置工作状态为出常温水
	        water::set_water_state(E_WATER_STATE_COMMON_WATER);

	    } else if (_s_cur_param.mode == E_WATER_MODE_ICE_WATER || _s_cur_param.water_temp == 10 || _s_cur_param.water_temp == 5) {
	        // 冰水模式 或 水温为 10℃ 或 5℃
	        if (isColdOpen()) {
	            // 检查是否可以启动定时器事件 "出水类型其他"
	            if (!is_can_start_auto_timer(E_TIMER_EVENT_ID_WATER_OPERATE_OTHER)) {
	            	LOGW_TRACE("出水冷水操作失败");
	                return false;  // 如果无法启动，则直接返回失败
	            }

	            // 停止零陈水A和LED灯自动关闭的定时器事件
	            water::stop_timer_event(E_TIMER_EVENT_ZERO_STATE_WATER_A);
	            water::stop_timer_event(E_TIMER_EVENT_WATER_LED_OFF);

	            // 设置任务负载，开启冰水相关的设备负载
	            water::set_task_load(E_TASK_ID_WATER_OPERATE, true, {E_DEV_LOAD_TYPE_DIAPHRAGM_PUMP, E_DEV_LOAD_TYPE_CLEANTANK2});

	            // 设置工作状态为出冰水
	            water::set_water_state(E_WATER_STATE_ICE_WATER);

	        } else {
	            // 如果制冷功能未开启，则提示用户需要先打开制冷功能
	            LOGD("冷水档位不可用,需先打开制冷功能");
	            // 可能显示某些窗口以提示用户（被注释掉的代码）
	            return false;  // 返回失败
	        }

	    } else {
	        // 其他模式（热水模式）
	        Global::Water::isStartHot = false;

	        // 静态变量，用于标记是否是首次使用热水
	        static bool is_first_hot_use = true;

	        // 检查是否可以启动定时器事件 "出水热水操作"
	        if (!is_can_start_auto_timer(E_TIMER_EVENT_ID_WATER_OPERATE_HOT)) {
	            return false;  // 如果无法启动，则直接返回失败
	        }

	        // 停止零陈水A和LED灯自动关闭的定时器事件
	        water::stop_timer_event(E_TIMER_EVENT_ZERO_STATE_WATER_A);
	        water::stop_timer_event(E_TIMER_EVENT_WATER_LED_OFF);

	        // 开启TDS传感器
	        protocol::setTds(true, false);

	        if (is_first_hot_use) {
	            // 首次使用热水时，执行防干烧保护
	            // 输出水温为25℃，出水量为当前参数中的设定值
	            protocol::startOutputWater(25, _s_cur_param.water_output);

	            // 标记首次使用完成
	            is_first_hot_use = false;

	            // 启动防干烧定时器事件
	            water::start_timer_event(E_TIMER_EVENT_WATER_PREVENT_DRY_BURNING);
	        } else {
	            // 非首次使用时，按照当前参数中的水温和出水量输出热水
	            protocol::startOutputWater(_s_cur_param.water_temp, _s_cur_param.water_output);
	        }

	        // 设置任务负载，开启热水相关的设备负载
	        water::set_task_load(E_TASK_ID_WATER_OPERATE, true,
	                             {E_DEV_LOAD_TYPE_UV_LIGHT, E_DEV_LOAD_TYPE_WATER_IN,
	                              E_DEV_LOAD_TYPE_AIR_PUMP, E_DEV_LOAD_TYPE_LED_LIGHT});

	        // 设置工作状态为出热水
	        water::set_water_state(E_WATER_STATE_HOT_WATER);
	    }

	    // 重置水流量相关变量
	    Global::Water::last_water_value = 0;
	    Global::Water::water_value = 0;

	    // 关闭屏幕自动计数功能
	    LOCK_SCREEN->set_auto_count(false);

	    // 更新UI，显示出水状态
	    ui_water_output(true);
	return true;
}


// 该定时任务回调函数只用来处理 UI 相关的逻辑
static void _on_timer_event_cb_ui(int id, int run_time, int total_time, void *user_data) {
    if (id == E_TIMER_EVENT_FILTER_BRASH) {
        // 滤芯刷洗事件
        if (run_time == START_TIME_POINT) {
            // 开始时间点，暂无操作
        } else if (run_time == FILTER_BRASH_TIME_POINT) {
            // 刷洗完成时隐藏导航栏，并启用自动计数功能
            EASYUICONTEXT->hideNaviBar();
            LOCK_SCREEN->set_auto_count(true);
        }
    }

    else if (id == E_TIMER_EVENT_WATER_PREVENT_DRY_BURNING) {
        // 防干烧事件
        if (run_time == START_TIME_POINT) {
            // 开始时间点，暂无操作
        } else if (run_time == PREVENT_DRY_BURNING_TIME_POINT) {
            // 在防干烧完成后，启动出水操作，设置为当前水温
            protocol::startOutputWater(_s_cur_param.water_temp, _s_cur_param.water_output, true, false);

            // 停止出水（处理热水缺水问题）
            // stop_water_output(water_value < _s_cur_param.water_output ? water_value : _s_cur_param.water_output, true);
        }
    }
    else if (id == E_TIMER_EVENT_WATER_HOT_WATER_DELAY) {
        // 热水延时事件
        if (run_time == START_TIME_POINT) {
            // 开始时间点，暂无操作
        } else if (run_time == HOT_WATER_DELAY_TIME_POINT) {
            // 延时结束后停止出水
            stop_water_output(Global::Water::water_value < _s_cur_param.water_output ?
                              Global::Water::water_value : _s_cur_param.water_output, true);
        }
    }
    else if (id == E_TIMER_EVENT_ZERO_STATE_WATER_A) {
        // 零陈水 A 事件
        Global::Timer::CountS = run_time;  // 更新零陈水 A 的运行时间
        if (run_time == START_TIME_POINT) {
            // 开始时间点，停止零陈水 B 事件，并设置总时间为第一个阶段的时间点
            water::stop_timer_event(E_TIMER_EVENT_ZERO_STATE_WATER_B);
            Global::Timer::totalCount = ZERO_STATE_WATER_A1_TIME_POINT;
        }
        else if (run_time == ZERO_STATE_WATER_A1_TIME_POINT) {
            // 第一阶段完成，设置总时间为第二阶段的时间点
            Global::Timer::totalCount = ZERO_STATE_WATER_A2_TIME_POINT;
        }
        else if (run_time == ZERO_STATE_WATER_A2_TIME_POINT) {
            // 第二阶段完成，设置总时间为第三阶段的时间点
            Global::Timer::totalCount = ZERO_STATE_WATER_A3_TIME_POINT;
        }
        else if (run_time == ZERO_STATE_WATER_A3_TIME_POINT) {
            // 第三阶段完成，设置总时间为第四阶段的时间点
            Global::Timer::totalCount = ZERO_STATE_WATER_A4_TIME_POINT;
        }
        else if (run_time == ZERO_STATE_WATER_A4_TIME_POINT) {
            // 第四阶段完成，启动零陈水 B 事件
            water::start_timer_event(E_TIMER_EVENT_ZERO_STATE_WATER_B);
        }
    }
    else if (id == E_TIMER_EVENT_ZERO_STATE_WATER_B) {
        // 零陈水 B 事件
        Global::Timer::Counth = run_time;  // 更新零陈水 B 的运行时间
        if (run_time == START_TIME_POINT) {
            // 开始时间点，设置总时间为第一个阶段的时间点
            Global::Timer::htotalCount = ZERO_STATE_WATER_B1_TIME_POINT;
        }
        else if (run_time == ZERO_STATE_WATER_B1_TIME_POINT) {
            // 第一阶段完成，设置总时间为第二阶段的时间点
            Global::Timer::htotalCount = ZERO_STATE_WATER_B2_TIME_POINT;
        }
        else if (run_time == ZERO_STATE_WATER_B2_TIME_POINT) {
            // 第二阶段完成，设置总时间为第三阶段的时间点
            Global::Timer::htotalCount = ZERO_STATE_WATER_B3_TIME_POINT;
        }
        else if (run_time == ZERO_STATE_WATER_B3_TIME_POINT) {
            // 第三阶段完成，设置总时间为第四阶段的时间点
            Global::Timer::htotalCount = ZERO_STATE_WATER_B4_TIME_POINT;
        }
        else if (run_time == ZERO_STATE_WATER_B4_TIME_POINT) {
            // 第四阶段完成，重置设备负载状态，并重新启动零陈水 B 事件
            LOGD("reset");
            water::set_task_load(E_TASK_ID_ZERO_STATE_WATER, false, {
                E_DEV_LOAD_TYPE_UV_LIGHT, E_DEV_LOAD_TYPE_WATER_IN,
                E_DEV_LOAD_TYPE_AIR_PUMP, E_DEV_LOAD_TYPE_WASTE_WATER});
            water::start_timer_event(E_TIMER_EVENT_ZERO_STATE_WATER_B);
        }
    }
    else if (id == E_TIMER_EVENT_ICE_ADD_WATER) {
        // 冰水箱补水事件
        if (run_time == START_TIME_POINT) {
            // 开始时间点，暂无操作
        } else if (run_time == ICE_ADD_WATER_TIME_POINT) {
            // 加水完成时隐藏导航栏，并重新启动零陈水 A 事件
            EASYUICONTEXT->hideNaviBar();
            water::stop_timer_event(E_TIMER_EVENT_ZERO_STATE_WATER_A);
            water::start_timer_event(E_TIMER_EVENT_ZERO_STATE_WATER_A);
        }
    }
    else if (id == E_TIMER_EVENT_OUT_ICE) {
//    	LOGD_TRACE("出冰运行时间%d",run_time);
        // 出冰
        if (run_time == START_TIME_POINT) {
            // 开始时间点，暂无操作
        } else if (run_time == total_time) {
            ui_iceing_output(false);
        }
    }
    else if (id == E_TIMER_EVENT_ICE_ADD_BLOCK) {
    	char buf [1024]={0};
    	snprintf (buf,sizeof(buf),"%s:%d","制冰箱补水中，运行时间",run_time);
    	mTextView8Ptr->setText(buf);
    }else if (id == E_TIMER_EVENT_MAKE_ICEPUMP) {
    	char buf [1024]={0};
    	snprintf (buf,sizeof(buf),"%s:%d","制冰泵间隔启动中，运行时间",run_time);
    	if(run_time == total_time){
    		snprintf (buf,sizeof(buf),"%s:%d","制冰泵持续开启，时间",run_time);
    	}
    	mTextView8Ptr->setText(buf);
    }else if (id == E_TIMER_EVENT_MAKE_ALLICE) {
    	if(run_time < total_time -60)
    	{
        	char buf [1024]={0};
        	snprintf (buf,sizeof(buf),"%s:%d","水温<1°开始制冰，运行时间",run_time);
        	mTextView8Ptr->setText(buf);
    	}else{
        	char buf [1024]={0};
        	snprintf (buf,sizeof(buf),"%s:%d","打开“推杆电机正”，运行时间",run_time);
        	mTextView8Ptr->setText(buf);
    	}
    }else if (id == E_TIMER_EVENT_ROD_MOTOR) {
    	char buf [1024]={0};
    	snprintf (buf,sizeof(buf),"%s:%d","电机复位中，运行时间",run_time);
    	mTextView8Ptr->setText(buf);
    }




}

/*
 * @breif ModeCount打印显示信息
 *
 */
static void LOGDText(std::string Tip,ZKTextView* mTextViewkPtr,const int ISopen){
	char buf [1024]={0};
	snprintf (buf,sizeof(buf),"%s:%d",Tip.c_str(),ISopen);
	mTextViewkPtr->setText(buf);
}
static void LOGDSText(std::string Tip,ZKTextView* mTextViewkPtr,std::string ISopen){
	char buf [1024]={0};
	snprintf (buf,sizeof(buf),"%s:%s",Tip.c_str(),ISopen.c_str());
	mTextViewkPtr->setText(buf);
}
//text
/*
 * @breif 显示打印内容
 *
 */
static void ShowText(){
//   LOGDText("常温ntc",mTextView6Ptr,getProtocolData().NorNTC);
   LOGDText("冰水ntc",mTextView7Ptr,getProtocolData().inquiry_e5_b2.booster_pump_ad_value);
//   getProtocolData().inquiry_e5_b2.clear_water_low_level ? LOGDText("净水箱低水位",mTextView8Ptr,1):LOGDText("净水箱低水位",mTextView8Ptr,0);
////   getProtocolData().inquiry_e5_b2.clear_water_low_level ? LOGDText("净水箱高水位",mTextView9Ptr,1):LOGDText("净水箱高水位",mTextView9Ptr,0);
//   getProtocolData().inquiry_e5_b2.clear_water_low_level ? LOGDText("净水箱中水位",mTextView9Ptr,1):LOGDText("净水箱中水位",mTextView10Ptr,0);
//   LOGDText("机器状态",mTextView10Ptr,getProtocolData().WaterDispenserStatus);
//   LOGDText("压缩工作状态",mTextView11Ptr, getProtocolData().isCompressorStarted());
   LOGDText("常温水/冰水当前出水量",mTextView12Ptr, getProtocolData().inquiry_e5_b2.hot_tank_ntc_temp);
   LOGDText("设定出水量 ",mTextView13Ptr,_s_cur_param.water_output);
   LOGDText("热水当前出水量",mTextView14Ptr,getProtocolData().inquiry_a5.output_water_output);

   LOGDText("原水TDS1",mTextView17Ptr,getProtocolData().inquiry_e5_b2.tds1_value);
   LOGDText("净水TDS2",mTextView18Ptr,getProtocolData().inquiry_e5_b2.tds2_value);
   LOGDText("出水指令",mTextView19Ptr,getProtocolData().inquiry_a5.output_water_control);
   LOGDText("制冷状态",mTextView20Ptr,getProtocolData().inquiry_e5_b2.raw_water_mid_level);
   LOGDText("保温状态",mTextView22Ptr,getProtocolData().inquiry_e5_b2.raw_water_low_level);
//   ICEWATERTANK->isStarted()?LOGDText("冰水线程是否运行",mTextView20Ptr,1):LOGDText("冰水线程是否运行",mTextView20Ptr,0);
   LOGDText("冰胆补水时间:",mTextView21Ptr,Global::Water::bushuiCount);
   LOGDText("冰胆排水时间",mTextView25Ptr,Global::Water::paishuiCount);
//   std::string TipText="uv灯状态：";
//   TipText+=UVLED->RetTip();
//   mTextView22Ptr->setText(TipText.c_str());
//   getProtocolData().A1Byte2.bits.b7? LOGDText("压缩机工作",mTextView23Ptr,1):LOGDText("压缩机工作",mTextView23Ptr,0);
   LOGDText("外供净水",mTextView24Ptr,getProtocolData().inquiry_e5_b2.clear_water_high_level);
//   LOGDText("连续制水倒计时",mTextView26Ptr,EXTERNALPURIFIEDWATERSUPPLY->RetCount());
   LOGDText("制水连续30min",mTextView27Ptr,Global::Water::waterTimeOut);

   LOGDText("增压泵状态",mTextView76Ptr,getProtocolData().inquiry_e5_b2.create_water_pump_state);
   LOGDText("出水温度",mTextView5Ptr,getProtocolData().inquiry_a5.output_water_temp);
   LOGDText("10min计时",mTextView34Ptr,Global::Timer::CountS);
   LOGDText("8h零陈水总时长",mTextView75Ptr,ZERO_STATE_WATER_B4_TIME_POINT);
   LOGDText("10min零陈水总时长",mTextView71Ptr,ZERO_STATE_WATER_A4_TIME_POINT);
   LOGDText("8h计时",mTextView72Ptr,Global::Timer::Counth);
   LOGDText("8h目标时间",mTextView74Ptr,Global::Timer::htotalCount);
   LOGDText("10min目标时间",mTextView46Ptr,Global::Timer::totalCount);
   LOGDText("出水速度",mTextView47Ptr,Global::Water::water_speed);
   LOGDText("滤芯寿命PPC（ml）",mTextView38Ptr, water::get_cartridge_life_flow(E_CARTRIDGE_TYPE_PPC));
   LOGDText("滤芯寿命RO（ml）",mTextView48Ptr,water::get_cartridge_life_flow(E_CARTRIDGE_TYPE_RO));
   LOGDText("滤芯寿命C2（ml）",mTextView49Ptr,water::get_cartridge_life_flow(E_CARTRIDGE_TYPE_C2));
   LOGDText("上电寿命（s）",mTextView39Ptr, water::get_cartridge_life_second(E_CARTRIDGE_TYPE_PPC));
   LOGDText("冰胆自动检测时间（s）",mTextView50Ptr,Global::Water::Count);
   LOGDText("漏水状态",mTextView54Ptr,getProtocolData().inquiry_e5_b2.leak_state);
   LOGDText("7天累计时间",mTextView55Ptr,Global::Water::ColdWaterCount);
   LOGDText("冷水累计出水量",mTextView57Ptr,Global::Water::ColdWaterNum);
   LOGDText("冰胆排换水时间",mTextView58Ptr,Global::Water::bupaishuiCount);
   LOGDText("缺水状态",mTextView59Ptr,Global::Flags::LackOfWater);
   LOGDText("冰胆排换水补水数",mTextView61Ptr,getProtocolData().inquiry_e5_b2.hot_tank_ntc_temp);

   LOGDText("热水工作电流",mTextView67Ptr,getProtocolData().inquiry_e5_fa.water_hot_heating_pump);
//   LOGDText("热水工作电流（低位）",mTextView68Ptr,getProtocolData().inquiry_e5_fa.water_hot_heating_pump);
   LOGDSText("电源板A5数据",mTextView64Ptr, Global::Log::inquiry_a5_log);
   LOGDSText("电源板E5B2数据",mTextView65Ptr, Global::Log::inquiry_e5_b2_log);
   LOGDSText("电源板E5FA数据",mTextView66Ptr, Global::Log::inquiry_e5_fa_log);
   LOGDSText("中间板A2",mTextView68Ptr, Global::Log::inquiry_a2_log);
   LOGDText("增压泵电流值AD",mTextView69Ptr,getProtocolData().inquiry_e5_b2.booster_pump_ad_value);
   LOGDText("进水温度",mTextView70Ptr,getProtocolData().inquiry_a5.input_water_temp);
//   LOGDText("电源板数据",mTextView64Ptr,DEBUG_PRO_DATA);

  // ()/*PURECHENSHUINEW->Zerochenshuisteps - (base::uptime() / 1000)*/
//   LOGD("--%d-- Zerochenshuisteps: %d", __LINE__, PURECHENSHUINEW->Zerochenshuisteps);

   mListView_load_statePtr->refreshListView();

   // 打印日志，显示 TDS1 和 TDS2 的开关状态
   LOGDText("tds1开关", mTextView40Ptr, protocol::getLoadSwitch(E_DEV_LOAD_TYPE_TDS1));
   LOGDText("tds2开关", mTextView43Ptr, protocol::getLoadSwitch(E_DEV_LOAD_TYPE_TDS2));

   LOGDText("脱冰感应AD",mTextView15Ptr,getProtocolData().inquiry_a2.DeicingSensorAD);
   LOGDText("接水盒排水泵AD",mTextView16Ptr,getProtocolData().inquiry_a2.DrainBoxPumpAD);
   LOGDText("制冰水箱温度",mTextView23Ptr,Cur_a2.IceMakingWaterNTCTemp);
   LOGDText("冰水箱温度",mTextView29Ptr,Cur_a2.ColdWaterTankNTCTemp);
   LOGDText("冰满AD",mTextView30Ptr,getProtocolData().inquiry_a2.IceFullAD);
   LOGDText("制冰泵AD",mTextView31Ptr,getProtocolData().inquiry_a2.IceMakingPumpAD);
   LOGDText("冰水箱浮球高",mTextView32Ptr,getProtocolData().inquiry_a2.ColdWaterTankHighLevel);
   LOGDText("冰水箱浮球低",mTextView51Ptr,getProtocolData().inquiry_a2.ColdWaterTankLowLevel);
   LOGDText("制冰水位",mTextView52Ptr,getProtocolData().inquiry_a2.IceMakingWaterLevel);
   LOGDText("出冰微动开关",mTextView53Ptr,getProtocolData().inquiry_a2.IceDispenserMicroSwitch);
   LOGDText("冷水箱防冻",mTextView60Ptr,getProtocolData().inquiry_a2.RespColdWaterTankAntiFreeze);
   LOGDText("检测微动开关",mTextView63Ptr,getProtocolData().inquiry_a2.DetectionMicroSwitch);
}

/*
 * @breif 打印信息是否开启
 * @param  true 开启打印信息  false 关闭打印信息
 */
static void DisplayPrinting(bool IsOpen){
	mWindowLogPtr->setVisible(IsOpen);
	mWindowLogPtr->setTouchPass(true);
}

namespace{
static IMEContext::SIMETextInfo mTextInfo;
//WiFi名称
static std::string mWiFiName;
class ImeContent : public IMEContext::IIMETextUpdateListener
{
public:
	virtual ~ImeContent() { }
	virtual void onIMETextUpdate(const std::string &text)
	{
		if(Global::Water::is_increace){
			_s_cur_param.mode = E_WATER_MODE_SELF;
		}

		SBaseItem item = {0, _s_cur_param.mode,text,"main/空杯@1x.png",_s_cur_param.water_output,_s_cur_param.water_temp};
		open_app("AddEffluentModeActivity",item);
	}
};
static ImeContent mImeContent;

class PointSeekListener : public ZKSeekBar::ISeekBarChangeListener{
public:
	virtual void onProgressChanged(ZKSeekBar *pSeekBar, int progress){

		if(pSeekBar->getID() == ID_MAIN_SeekBarTemp){
	    	_s_cur_param.water_temp = _s_cur_opt.water_temp.min + progress * _s_cur_opt.water_temp.step;
	    	if(Global::Other::water_index < water::get_self_mode_count()) {
	    		SModeInfoEx ex = water::get_self_mode(Global::Other::water_index);
				if(ex.option.water_temp.def != 25 && ex.option.water_temp.def != 10) {
					ex.option.water_temp.def = _s_cur_param.water_temp;
	//				water::reset_self_mode(Global::Other::water_index, ex);
				}
	    	}
	    	if(progress == 11){
	    		mCurTempPtr->setText(98);
	    	}else{
	    		mCurTempPtr->setText(_s_cur_param.water_temp);
	    	}
		}

		else if(pSeekBar->getID() == ID_MAIN_SeekBarYield){

	    	if(progress == 18){
	    		mYieldTipPtr->setVisible(true);
	    		mCurYieldPtr->setVisible(false);
	    		mTextView11Ptr->setVisible(false);
	    		_s_cur_param.water_output = BEST_HIGH_WATER;
	    	}
	    	else{
	    		mYieldTipPtr->setVisible(false);
	    		mCurYieldPtr->setVisible(true);
	    		mTextView11Ptr->setVisible(true);
	        	_s_cur_param.water_output = _s_cur_opt.water_output.min +progress * _s_cur_opt.water_output.step;
	    	}

	    	if(water::get_self_mode(Global::Other::water_index).option.mode != E_WATER_MODE_SELF) {
	    		SModeInfoEx ex = water::get_self_mode(Global::Other::water_index);
				ex.option.water_output.def = _s_cur_param.water_output;
				water::reset_self_mode(Global::Other::water_index, ex);
	    	}

	    	mCurYieldPtr->setText(_s_cur_param.water_output);
		}

		else if(pSeekBar->getID() == ID_MAIN_IceTimeBar){
//			LOGI_TRACE("出水量范围：%d~%d, 步长：%d" ,_s_cur_opt.water_output.min,_s_cur_opt.water_output.max ,_s_cur_opt.water_output.step);

	    	if(progress == 29){
	    		mtimeTipPtr->setVisible(true);
	    		mCurTimePtr->setVisible(false);
	    		mTextView73Ptr->setVisible(false);
	    		_s_cur_param.water_output = BEST_HIGH_WATER;
	    	}
	    	else{
	    		mtimeTipPtr->setVisible(false);
	    		mCurTimePtr->setVisible(true);
	    		mTextView73Ptr->setVisible(true);
	        	_s_cur_param.water_output = _s_cur_opt.water_output.min +progress * _s_cur_opt.water_output.step;
	    	}
	    	if(water::get_self_mode(Global::Other::water_index).option.mode != E_WATER_MODE_SELF) {
	    		SModeInfoEx ex = water::get_self_mode(Global::Other::water_index);
				ex.option.water_output.def = _s_cur_param.water_output;
				water::reset_self_mode(Global::Other::water_index, ex);
	    	}

	    	mCurTimePtr->setText(_s_cur_param.water_output);
		}

	}
};
static PointSeekListener seekListener;
static TouchClass touchTemp;
static TouchClass touchYield;
};

bool operateIceCake(bool on) {
	if(on){
		water::stop_timer_event(E_TIMER_EVENT_WATER_LED_OFF);
		LOGD_TRACE("出冰时间%d",_s_cur_param.water_output + 2);
		//出冰时间
		water::start_timer_event(E_TIMER_EVENT_OUT_ICE, _s_cur_param.water_output + 2);
	}else{
	    water::stop_timer_event(E_TIMER_EVENT_WATER_LED_OFF);
	    if(Global::Water::ledType){
	    	water::start_timer_event(E_TIMER_EVENT_WATER_LED_OFF, Global::Water::ledTime);
	    	// LED照明灯在出水结束后若1分钟内无任何操作时自动关闭
	    }
	    water::stop_timer_event(E_TIMER_EVENT_OUT_ICE);
	}
    // 更新UI，显示出冰状态
    ui_iceing_output(on);
	return true;
}

bool operateWater(bool on) {
	if(on){
		return start_water_output();
	}else{
		if (water::get_water_state() != E_WATER_STATE_IDLE) {
			if (water::get_water_state() == E_WATER_STATE_HOT_WATER) {
				return stop_water_output(Global::Water::water_value < _s_cur_param.water_output ? Global::Water::water_value : _s_cur_param.water_output);
			} else {
				return stop_water_output(getProtocolData().inquiry_e5_b2.hot_tank_ntc_temp);
			}
		} else {
//			stop_water_output(0);
		}
	}
	return true;
}

bool stop_water(bool is_auto_stop){
	 if(water::get_water_state() != E_WATER_STATE_IDLE){
		if(water::get_water_state() == E_WATER_STATE_HOT_WATER) {
			stop_water_output(Global::Water::water_value < _s_cur_param.water_output ? Global::Water::water_value : _s_cur_param.water_output, is_auto_stop);
		}else{
			stop_water_output(getProtocolData().inquiry_e5_b2.hot_tank_ntc_temp, is_auto_stop);
		}
	}else{
		stop_water_output(0, is_auto_stop);
	}
	 return true;
}

static void Attribute_init(){
	EASYUICONTEXT->hideNaviBar();
	mWaterWndPtr->hideWnd();

	mTextCollectPtr->setTouchPass(true);
	mTextWaterPtr->setTouchPass(true);
	mTextView2Ptr->setTouchPass(true);
	mTextView5Ptr->setTouchPass(true);
	mTextView3Ptr->setTouchPass(true);
	mTempTextPtr->setTouchPass(true);

	// 初始化
	touchTemp.setValues(mTempText_Ptr, mTempText_Ptr->getPosition(), 658, false);
	touchYield.setValues(mYieldTextPtr, mYieldTextPtr->getPosition(), 658);
	//注册监听滑块
	mSeekBarTempPtr->setTouchListener(&touchTemp);
	mSeekBarYieldPtr->setTouchListener(&touchYield);
	mIceTimeBarPtr->setTouchListener(&touchYield);

	mSeekBarTempPtr->setSeekBarChangeListener(&seekListener);
	mSeekBarYieldPtr->setSeekBarChangeListener(&seekListener);
	mIceTimeBarPtr->setSeekBarChangeListener(&seekListener);
}

static void PowerOffMemory(){
	Global::Water::BoilingPoint = StoragePreferences::getInt("BoilingPoint", 95);
	Global::Flags::TouchSound = StoragePreferences::getBool("TouchSound", true);
	SCREEN_LOCK_TIME = StoragePreferences::getInt("LockTime", SCREEN_LOCK_TIME);
//	Global::Water::waterLed = StoragePreferences::getInt("waterLed", 0);
}

static S_ACTIVITY_TIMEER REGISTER_ACTIVITY_TIMER_TAB[] = {
	//{0,  6000}, //定时器id=0, 时间间隔6秒
	{1, 1000},
	{2, 1000},
};

/**
 * 当界面构造时触发
 */
static void onUI_init(){
	Global::Flags::is_init_ui = true;
	//控件初始化
	Attribute_init();
    protocol::closeAllValve();
    protocol::stopOutputWater();
//	StoragePreferences::clear();
	//自定义按键音
	hw::init();
	water::init();

	//初始化定时任务回调
	water::add_timer_event_ui(_on_timer_event_cb_ui);
	PowerOffMemory();

	brash_thread.run("power on brash");

	//每次上电设置电机功率
	protocol::setAA_E1();
#if 1
	if(base::read_all("/data/zkota.conf") != base::read_all("/res/ui/zkota.conf")){
		base::copy_file("/res/ui/zkota.conf", "/data/zkota.conf");
	}
	//防砖程序标识位
	SystemProperties::setString("sys.zkapp.state", "running");
#endif

}

/**
 * 当切换到该界面时触发
 */
static void onUI_intent(const Intent *intentPtr) {
    if (intentPtr != NULL) {
        //TODO
    }
}

/*
 * 当界面显示时触发
 */
static void onUI_show() {

}

/*
 * 当界面隐藏时触发
 */
static void onUI_hide() {
	LOGW_TRACE("main_hide");
	//跳转其他界面停水
	if(water::get_water_state() != E_WATER_STATE_IDLE){
		operateWater(false);
		operateIceCake(false);
	}
}

/*
 * 当界面完全退出时触发
 */
static void onUI_quit() {
	water::remove_timer_event_ui(_on_timer_event_cb_ui);
	misc::image_cache_release();
	mSeekBarTempPtr->setTouchListener(nullptr);
	mSeekBarYieldPtr->setTouchListener(nullptr);
	mIceTimeBarPtr->setTouchListener(nullptr);

	mSeekBarTempPtr->setSeekBarChangeListener(nullptr);
	mSeekBarYieldPtr->setSeekBarChangeListener(nullptr);
	mIceTimeBarPtr->setSeekBarChangeListener(nullptr);
}

static void handleHotWater(const SProtocolData &data) {
    if (water::get_water_state() == E_WATER_STATE_HOT_WATER) {
        if (data.inquiry_a5.output_water_control == 1) {
            Global::Water::isStartHot = true;
        }

        if (Global::Water::isStartHot) {
            // 计算累计出水量
            if (data.inquiry_a5.output_water_output < Global::Water::last_water_value) {
                Global::Water::last_water_value = data.inquiry_a5.output_water_output;
            } else {
                Global::Water::water_value += data.inquiry_a5.output_water_output - Global::Water::last_water_value;
                Global::Water::last_water_value = data.inquiry_a5.output_water_output;
            }

            // 计算出水速度 (每秒计算一次)
            if (base::uptime() - Global::Water::speed_last_time > 1000) {
                Global::Water::water_speed = Global::Water::water_value - Global::Water::speed_last_water_num;
                Global::Water::water_speed = Global::Water::water_speed * 60; // 转换为 ml/min
                Global::Water::speed_last_water_num = Global::Water::water_value;
                Global::Water::speed_last_time = base::uptime();
            }

            // 剩余水量少于40ml时，将出水温度提升到95度
            if ((_s_cur_param.water_output - Global::Water::water_value < 40) &&
                data.inquiry_a5.output_water_temp >= 60 && data.inquiry_a5.output_water_temp <= 85) {

                protocol::startOutputWater(95, _s_cur_param.water_output, true, false);
            }

            // 达到设定出水量或实际出水量达到上限时停止出水
            if (Global::Water::water_value >= (_s_cur_param.water_output >= 350 ? _s_cur_param.water_output + 15 : _s_cur_param.water_output) ||
                data.inquiry_a5.output_water_output >= (_s_cur_param.water_output >= 350 ? _s_cur_param.water_output + 15 : _s_cur_param.water_output)) {
                stop_water_output(_s_cur_param.water_output, true);

            }
        }
    }
}

static void handleColdOrNormalWater(const SProtocolData &data) {
    if (water::get_water_state() == E_WATER_STATE_ICE_WATER || water::get_water_state() == E_WATER_STATE_COMMON_WATER) {
        // 冰水模式下，计算冷水出水量
        if (water::get_water_state() == E_WATER_STATE_ICE_WATER) {
            static int last_num = data.inquiry_e5_b2.hot_tank_ntc_temp;
            if (last_num < data.inquiry_e5_b2.hot_tank_ntc_temp) {
                Global::Water::ColdWaterNum += data.inquiry_e5_b2.hot_tank_ntc_temp - last_num;
                if (Global::Water::ColdWaterNum > 800) {
                    Global::Water::ColdWaterCount = 0;
                    Global::Water::ColdWaterNum = 0;
                }
                last_num = data.inquiry_e5_b2.hot_tank_ntc_temp;
            } else {
                last_num = data.inquiry_e5_b2.hot_tank_ntc_temp;
            }
        }

        // 计算出水速度 (每秒计算一次)
        if (base::uptime() - Global::Water::speed_last_time > 1000) {
            Global::Water::water_speed = data.inquiry_e5_b2.hot_tank_ntc_temp - Global::Water::speed_last_water_num;
            Global::Water::water_speed = Global::Water::water_speed * 60; // 转换为 ml/min
            Global::Water::speed_last_water_num = data.inquiry_e5_b2.hot_tank_ntc_temp;
            Global::Water::speed_last_time = base::uptime();
        }

        // 达到设定出水量后停止出水
        if (data.inquiry_e5_b2.hot_tank_ntc_temp >= _s_cur_param.water_output) {
            stop_water_output(_s_cur_param.water_output, true);

        }

        // 缺水线程判断 (TODO: 待实现)
        // if (RewaterIntakingFalg) {
        //     HYDTHREAD->SaveTyield(data.inquiry_e5_b2.hot_tank_ntc_temp);
        // }
    }
}

static void handleMaxWaterOutput(const SProtocolData &data) {
    // 单次出水量达到4800ml时停止出水
    if (_s_cur_param.water_output >= 4800) {
    	static int64_t start_time = 0; // 静态变量保存开始出水的时间
    	if(water::get_water_state() != E_WATER_STATE_IDLE){
    	  if (start_time == 0) { // 如果是第一次进入这个状态
    	    start_time = base::uptime(); // 记录当前时间
    	    LOGD("__________WATER OUTPUT STARTED........"); // 可选：记录出水开始
    	  }

    	  if (base::uptime() - start_time > 5000) { // 出水5秒后才进行判定 (5000 milliseconds = 5 seconds)
    	    LOGD("__________MAX WATER STOP........");
//    	    stop_water_output(_s_cur_param.water_output, true);
//    	    start_time = 0; // 重置 start_time，以便下次出水时重新计时
    	  }
    	} else {
    	  start_time = 0; // 如果当前不是出水状态，重置 start_time
    	}
    }
}



/**
 * 串口数据回调接口
 */
static void onProtocolDataUpdate(const SProtocolData &data) {
    // 更新全局水温
    Global::Water::RelaTemp = data.inquiry_a5.input_water_temp;

    if (Global::Flags::is_init_ui) {
        // 处理热水逻辑
        handleHotWater(data);

        // 处理冰水/常温水逻辑
        handleColdOrNormalWater(data);

        // 处理最大出水量限制
        handleMaxWaterOutput(data);
    }

}

/**
 * 定时器触发函数
 * 不建议在此函数中写耗时操作，否则将影响UI刷新
 * 参数： id
 *         当前所触发定时器的id，与注册时的id相同
 * 返回值: true
 *             继续运行当前定时器
 *         false
 *             停止运行当前定时器
 */
static bool onUI_Timer(int id){
	switch (id) {
	case 1:{
	     //打印信息
	      if (Global::Flags::IsCodeFalg) {
	        DisplayPrinting(true);
	        ShowText();
	      } else {
	        DisplayPrinting(false);
	      }
	}break;
	case 2:{
		Global::Water::ColdWaterCount++;
		if(!isColdOpen()){    //未制冷不计数
			Global::Water::ColdWaterCount = 0;
		}
		if(_s_cur_opt.mode == E_WATER_MODE_ICE_WATER ){
			mCurTempPtr->setText(int(Cur_a2.ColdWaterTankNTCTemp));
		}
	//	else if(_s_cur_opt.mode == E_WATER_MODE_ICE_WATER ){
	//		mCurTempPtr->setText(int(data.inquiry_a2.ColdWaterTankNTCTemp));
	//	}
	}break;
		default:
			break;
	}
    return true;
}

/**
 * 有新的触摸事件时触发
 * 参数：ev
 *         新的触摸事件
 * 返回值：true
 *            表示该触摸事件在此被拦截，系统不再将此触摸事件传递到控件上
 *         false
 *            触摸事件将继续传递到控件上
 */
static bool onmainActivityTouchEvent(const MotionEvent &ev) {
    switch (ev.mActionStatus) {
		case MotionEvent::E_ACTION_DOWN://触摸按下
			//LOGD("时刻 = %ld 坐标  x = %d, y = %d", ev.mEventTime, ev.mX, ev.mY);
			break;
		case MotionEvent::E_ACTION_MOVE://触摸滑动
			break;
		case MotionEvent::E_ACTION_UP:  //触摸抬起
			break;
		default:
			break;
	}
	return false;
}

struct ModeInfo {
    std::string icon;  // 图标
    std::string tip;   // 建议
};

// 使用 map 存储模式信息
std::map<EWaterMode, ModeInfo> modeMap = {
    {E_WATER_MODE_ICE, {"Water/Background_Water_Ice.png",
    		"方冰入杯来，饮品加冰，层次更出彩"}},
    {E_WATER_MODE_ICE_WATER, {"Water/Background_Water_IceWater.png",
    		"冰水超冰爽，慢饮细品身心更舒爽"}},
    {E_WATER_MODE_COMMON_WATER, {"Water/Background_Water_RoomTemp.png",
    		"健康成年人每天饮水量1500-2000ml水!"}},
    {E_WATER_MODE_RED_TEA, {"Water/Background_Water_BlackTea.png",
    		"红茶富含茶多酚、茶黄素等营养，常饮能有效增强人体免疫力"}},
    {E_WATER_MODE_BUBBLE_MILK, {"Water/Background_Water_MilkFormula.png",
    		"这个温度范围既有助于奶粉的充分溶解，又能最大程度地保留牛奶中的营养成分，如蛋白质、钙元素和B族维生素等"}},
    {E_WATER_MODE_HONEY_WATER, {"Water/Background_Water_Honey.png",
    		"运动后饮用蜂蜜水，能快速补充能量，缓解疲劳，帮助身体恢复元气"}},
    {E_WATER_MODE_GREEN_TEA, {"Water/Background_Water_GreenTea.png",
    		"喝绿茶具有多种功效与作用，包括抗氧化、提神醒脑、促进消化改善心血管健康等。"}},
    {E_WATER_MODE_FLAVOUR_TEA, {"Water/Background_Water_FlowerTea.png",
    		"喝花茶不仅可以品味到自然的馈赠，温暖心灵，芬芳时光，还能带来多种养生功效"}},
    {E_WATER_MODE_PU_ERH_TEA, {"Water/Background_Water_PuEr.png",
    		"喝普洱茶具有多种功效和作用，包括补充水分、提神醒脑、促进消化、促进排便养胃护胃、降脂减肥、抗衰老等。"}},
    {E_WATER_MODE_SELF, {"Water/Background_Water_Customize.png",
    		"自定义模式，根据个人喜好设置"}},
};

static void WaterUiClick(int index){
	if(_s_cur_opt.mode == E_WATER_MODE_ICE_WATER   && isColdOpen() == false){
		mWaterWndPtr->hideWnd();
		mrefrigerationWndPtr->showWnd();
		return;
	}else if(_s_cur_opt.mode == E_WATER_MODE_ICE   && isIceOpen() == false){
		mrefrigerationWndPtr->hideWnd();
		mWaterWndPtr->hideWnd();
		mIceMakingWndPtr->showWnd();
		return;
	}
	else{
		mWaterWndPtr->showWnd();
		mrefrigerationWndPtr->hideWnd();
		mIceMakingWndPtr->hideWnd();
	}


	SModeInfoEx interimInfo = water::get_self_mode(index);
	mTextViewtpdePtr->setText(interimInfo.name);

	mcoverWnd2Ptr->hideWnd();
	mcoverWndR2Ptr->hideWnd();
	mcoverWndRPtr->showWnd();
	mTempWndPtr->showWnd();
	mWinIcePtr->hideWnd();
	mTextWaterPtr->setText("出水");
	mtimeWndPtr->hideWnd();
	mIceTimeBarPtr->setVisible(false);
	if(_s_cur_opt.mode == E_WATER_MODE_ICE_WATER  || _s_cur_opt.mode == E_WATER_MODE_COMMON_WATER){
		mTextViewTempPtr->setText("实时温度");

		if(_s_cur_opt.mode != E_WATER_MODE_ICE_WATER ){
			mCurTempPtr->setText(_s_cur_opt.water_temp.def);
		}else{
			mCurTempPtr->setText(int(Cur_a2.ColdWaterTankNTCTemp));
		}

		mTextTempLPtr->setVisible(false);
		mTextTempRPtr->setVisible(false);
		mWinConstantPtr->hideWnd();
		//出水量进度刷新
		 int progress = GET_RANGE_PROGRESS(_s_cur_opt.water_output.min,
					_s_cur_opt.water_output.max,_s_cur_param.water_output,18);
		if(_s_cur_opt.water_output.max - _s_cur_opt.water_output.min != 0){
			mSeekBarYieldPtr->setProgress(progress);
			touchYield.setProgressByPercentage(progress / 18.0);
		}
	}else if(_s_cur_opt.mode == E_WATER_MODE_ICE){
		mTextViewTempPtr->setText("温度<0℃");
		mWinIcePtr->showWnd();
		mcoverWnd2Ptr->showWnd();
		mcoverWndR2Ptr->showWnd();
		mTempWndPtr->hideWnd();
		mcoverWndRPtr->hideWnd();
		mWinConstantPtr->hideWnd();
		mWinIcePtr->showWnd();
		mTextWaterPtr->setText("出冰");
		mtimeWndPtr->showWnd();
		mIceTimeBarPtr->setVisible(true);
		//出冰时间进度刷新
		 int progress = GET_RANGE_PROGRESS(_s_cur_opt.water_output.min,
					_s_cur_opt.water_output.max,_s_cur_param.water_output,29);
//		 LOGI_TRACE("当前progress：%d",progress);
		if(_s_cur_opt.water_output.max - _s_cur_opt.water_output.min != 0){
			mIceTimeBarPtr->setProgress(progress);
			touchYield.setProgressByPercentage(progress / 29.0);
		}
	}else{
		mWinConstantPtr->showWnd();
		mWinIcePtr->hideWnd();
		mTextTempLPtr->setVisible(true);
		mTextTempRPtr->setVisible(true);
		if(_s_cur_opt.water_temp.def == 100){
			mTextViewTempPtr->setText("水温98℃");
		}else{
			mTextViewTempPtr->setText("水温" + to_string(_s_cur_opt.water_temp.def) + "℃");
		}
		int progress = GET_RANGE_PROGRESS(_s_cur_opt.water_temp.min,
				_s_cur_opt.water_temp.max,_s_cur_param.water_temp,11);
		//温度进度刷新
		mSeekBarTempPtr->setProgress(progress);
		touchTemp.setProgressByPercentage(progress / 11.0);
		//出水量进度刷新
		 progress = GET_RANGE_PROGRESS(_s_cur_opt.water_output.min,
					_s_cur_opt.water_output.max,_s_cur_param.water_output,18);
		if(_s_cur_opt.water_output.max - _s_cur_opt.water_output.min != 0){
			mSeekBarYieldPtr->setProgress(progress);
			touchYield.setProgressByPercentage(progress / 18.0);
		}
	}
	//换背景
	auto it = modeMap.find(_s_cur_opt.mode);
	 if (it != modeMap.end()){
		 mTextTipPtr->setText(it->second.tip);
		 mWaterCmdPtr->setBackgroundPic(it->second.icon.c_str());
	 }


}
static int getListItemCount_MainList(const ZKListView *pListView) {
    //LOGD("getListItemCount_MainList !\n");
    return water::get_self_mode_count();
}

static void obtainListItemData_MainList(ZKListView *pListView,ZKListView::ZKListItem *pListItem, int index) {
    //LOGD(" obtainListItemData_ MainList  !!!\n");
		ZKListView::ZKListSubItem *sub1 = pListItem->findSubItemByID(ID_MAIN_SubItem1);
		ZKListView::ZKListSubItem *sub2 = pListItem->findSubItemByID(ID_MAIN_SubItem2);

		if(water::get_self_mode(index).collected_mode != E_WATER_MODE_NONE) {
			sub1->setText(water::get_self_mode(index).name);
			sub2->setText(water::get_self_mode(index).option.water_temp.def);

		}else{
			sub1->setText("");
			sub2->setText("");
		}
		pListItem->setBackgroundPic(water::get_self_mode(index).icon.c_str());
		misc::image_cache(water::get_self_mode(index).icon.c_str());
}

static void onListItemClick_MainList(ZKListView *pListView, int index, int id) {
    //LOGD(" onListItemClick_ MainList  !!!\n");
	pListView->beep();
	Global::Other::water_index = index;

	_s_cur_param.mode = water::get_self_mode(index).option.mode;
	_s_cur_param.water_temp = water::get_self_mode(index).option.water_temp.def;              //赋值温度
	_s_cur_param.water_output =  water::get_self_mode(index).option.water_output.def;
	_s_cur_opt = water::get_self_mode(index).option;

	LOGI_TRACE("当前出水温度：%d，出水量：%d",_s_cur_param.water_temp,_s_cur_param.water_output);

	LOGI_TRACE("当前温度范围：%d~%d，出水量范围：%d~%d",
			_s_cur_opt.water_temp.min,_s_cur_opt.water_temp.max,_s_cur_opt.water_output.min,_s_cur_opt.water_output.max);

	WaterUiClick(index);
}

static bool onButtonClick_outWater(ZKButton *pButton) {
    LOGD(" ButtonClick outWater !!!\n");
	if(water::is_timer_event_running(E_TIMER_EVENT_WATER_HOT_WATER_DELAY)){
		return false;
	}
	operateWater(!pButton->isSelected());

    return false;
}

static bool onButtonClick_collect(ZKButton *pButton) {
    LOGD(" ButtonClick collect !!!\n");
    return false;
}

static bool onButtonClick_outIce(ZKButton *pButton) {
    LOGD(" ButtonClick outIce !!!\n");
	if(water::is_timer_event_running(E_TIMER_EVENT_WATER_HOT_WATER_DELAY)){
		return false;
	}
	operateIceCake(!pButton->isSelected());
    return false;
}

const char * loadBuf[] = {
	  "常温阀（预留阀）",
	  "冷水放水阀（热水阀）",
	  "进水阀",
	  "废水阀",
	  "增压泵",
	  "回水阀",
	  "冷却阀",
	  "P203压缩机",
	  "LED照明灯",
	  "TDS1",
	  "TDS2",
	  "进气风扇",
	  "冷凝风扇",
	  "循环水泵",
	  "冰水箱进水阀",
	  "冷水隔膜泵",
	  "制冰泵",
	  "发热膜",
	  "脱冰阀",
	  "推杆电机正",
	  "推杆电机负",
	  "制冰水进水阀",
};

static int getListItemCount_ListView_load_state(const ZKListView *pListView) {
    //LOGD("getListItemCount_ListView_load_state !\n");
    return TAB_SIZE(loadBuf);
}

static void obtainListItemData_ListView_load_state(ZKListView *pListView,ZKListView::ZKListItem *pListItem, int index) {
    //LOGD(" obtainListItemData_ ListView_load_state  !!!\n");
	ZKListView::ZKListSubItem *pName = pListItem->findSubItemByID(ID_MAIN_SubItem_name);
	pName->setText(loadBuf[index]);
	pListItem->setText(protocol::getLoadSwitch((E_DEV_LOAD_TYPE)index));
}

static void onListItemClick_ListView_load_state(ZKListView *pListView, int index, int id) {
    //LOGD(" onListItemClick_ ListView_load_state  !!!\n");
}
static void onProgressChanged_SeekBarTemp(ZKSeekBar *pSeekBar, int progress) {
    //LOGD(" ProgressChanged SeekBarTemp %d !!!\n", progress);
}

static void onProgressChanged_SeekBarYield(ZKSeekBar *pSeekBar, int progress) {
    //LOGD(" ProgressChanged SeekBarYield %d !!!\n", progress);
}

static bool onButtonClick_refrigerationOn(ZKButton *pButton) {
    LOGD(" ButtonClick refrigerationOn !!!\n");
    mrefrigerationWndPtr->hideWnd();
    operateCold(true);
    mrefrigerTipWndPtr->showWnd();
    return false;
}

static bool onButtonClick_HideCold(ZKButton *pButton) {
    LOGD(" ButtonClick HideCold !!!\n");
    mrefrigerationWndPtr->hideWnd();
    return false;
}

static bool onButtonClick_IceOn(ZKButton *pButton) {
    LOGD(" ButtonClick IceOn !!!\n");
    mIceMakingWndPtr->hideWnd();
    operateIce(true);
    mIceTipWndPtr->showWnd();
    return false;
}

static bool onButtonClick_HideIce(ZKButton *pButton) {
    LOGD(" ButtonClick HideIce !!!\n");
    mIceMakingWndPtr->hideWnd();
    return false;
}
static bool onButtonClick_Button1(ZKButton *pButton) {
    LOGD(" ButtonClick Button1 !!!\n");
    mrefrigerTipWndPtr->hideWnd();
    return false;
}
static bool onButtonClick_Button2(ZKButton *pButton) {
    LOGD(" ButtonClick Button2 !!!\n");
    mIceTipWndPtr->hideWnd();
    return false;
}
static void onProgressChanged_IceTimeBar(ZKSeekBar *pSeekBar, int progress) {
    //LOGD(" ProgressChanged IceTimeBar %d !!!\n", progress);
}

